package com.kungfuhacking.wristbandpro.location.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.base.view.BaseActivity;
import com.kungfuhacking.wristbandpro.custom.TitleBarView;
import com.kungfuhacking.wristbandpro.location.bean.OldEntity;
import com.kungfuhacking.wristbandpro.location.presenter.IPickPresenter;
import com.kungfuhacking.wristbandpro.location.presenter.PickOldAdapter;
import com.kungfuhacking.wristbandpro.location.view.IPickView;
import com.kungfuhacking.wristbandpro.my.activity.AddOldActivity;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;
import com.kungfuhacking.wristbandpro.widget.swipe.DividerItemDecoration;
import com.kungfuhacking.wristbandpro.widget.swipe.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择定位老人页面
 * Created by Aaron on 17/5/3.
 */

public class PickOldActivity extends BaseActivity implements IPickView, SwipeRefreshLayout.OnRefreshListener {

    private RecyclerView recycleView;
    private List<OldEntity> oldEntities = new ArrayList<>();
    private IPickPresenter iPickPresenter = new IPickPresenter(this);
    private PickOldAdapter pickOldAdapter;
    private String TAG = getClass().getSimpleName();
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pick_old);
        initWidget();

    }

    @Override
    protected void onResume() {
        super.onResume();
        iPickPresenter.getAllOldInfo();
    }

    private void initWidget() {

        this.recycleView = (RecyclerView) findViewById(R.id.rv_list);
        TitleBarView tbv = (TitleBarView) findViewById(R.id.tbv);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        //为SwipeRefreshLayout设置监听事件
        swipeRefreshLayout.setOnRefreshListener(this);
//        //为SwipeRefreshLayout设置刷新时的颜色变化，最多可以设置4种
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        tbv.setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tbv.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加老人页面
                Bundle b = new Bundle();
                b.putBoolean("cancle", true);
                nextActivityWithBundle(AddOldActivity.class, b);
            }
        });
        initRecycleView();

    }

    private void initRecycleView() {

        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setItemAnimator(new DefaultItemAnimator());
        pickOldAdapter = new PickOldAdapter(this, oldEntities);
        recycleView.setAdapter(pickOldAdapter);
        recycleView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST,
                getResources().getDrawable(R.color.bg_gray)));
        recycleView.addOnItemTouchListener(new OnItemClickListener(recycleView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder holder, int position) {

                LogUtil.d(TAG, "选择的 老人:" + oldEntities.get(position).getName());

                SharedPreferences.Editor edit = sp.edit();
                edit.putString(Constant.CURRENTOLDID, oldEntities.get(position).getId());
                edit.putString(Constant.CURRENTOLDNAME, oldEntities.get(position).getName());
                edit.putInt(Constant.LEVEL, oldEntities.get(position).getLevel());
                edit.apply();
                finish();

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
            }
        });
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//dragFlags的时候，就会在长按item的时候进入拖动模式，然后就会一直回调onMove函数。我们可以在onMove中进行数据集的更新
                final int dragFlags;//用于拖拽的标志 如果是网格布局，拖动方向为上下左右，否则只有上下方向
                final int swipeFlags;//滑动标记

                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    swipeFlags = 0;
                } else {
//                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    dragFlags = 0;
                    swipeFlags = ItemTouchHelper.START;
//                    ItemTouchHelper.START | ItemTouchHelper.END;
                }
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

//                LogUtil.d(TAG, "=== onMove ====== ");
//                int fromPosition = viewHolder.getAdapterPosition();
//                int toPosition = target.getAdapterPosition();
//                LogUtil.e(TAG, "拖动listview " + fromPosition + ", to : " + toPosition);
//                data.add(toPosition, data.remove(fromPosition));
//                adapter.notifyItemMoved(fromPosition, toPosition);
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
//                LogUtil.d(TAG, "=== onSwiped ====== " + position);
                iPickPresenter.deleteOld(oldEntities.get(position).getId(), position);

            }

        });
        itemTouchHelper.attachToRecyclerView(recycleView);
    }

    /**
     * 删除成功后更新数据
     *
     * @param position
     */
    @Override
    public void updateDeleteInfo(int position) {

        String deleteId = oldEntities.get(position).getId();
        oldEntities.remove(position);
        //删除的是当前选择的老人, 则默认选择当前列表中的第一个老人
        if (deleteId.equals(sp.getString(Constant.CURRENTOLDID, ""))) {
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(Constant.CURRENTOLDID, oldEntities.size() > 0 ? oldEntities.get(0).getId() : "");
            edit.putString(Constant.CURRENTOLDNAME, oldEntities.size() > 0 ? oldEntities.get(0).getName() : "");
            edit.putInt(Constant.LEVEL, oldEntities.size() > 0 ? oldEntities.get(0).getLevel() : 0);
            edit.apply();
        }
        pickOldAdapter.notifyItemRemoved(position);

    }

    @Override
    public void setOldList(List<OldEntity> oldList) {
        oldEntities = oldList;
        pickOldAdapter.setOldEntities(oldList);
        pickOldAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iPickPresenter.clearRequest();
    }

    @Override
    public void onRefresh() {
        oldEntities.clear();
        pickOldAdapter.setOldEntities(oldEntities);
        pickOldAdapter.notifyDataSetChanged();
        iPickPresenter.getAllOldInfo();
        //结束后停止刷新
        swipeRefreshLayout.setRefreshing(false);
    }
}
